import { _decorator, Animation, AudioClip, CCFloat, Collider2D, Component, Contact2DType, EventTouch, Input, input, IPhysics2DContact, Node, RigidBody2D, Vec2 } from 'cc';
import { Tags } from './Tags';
import { AudioMgr } from './AudioMgr';
const { ccclass, property } = _decorator;

@ccclass('Bird')
export class Bird extends Component {
    private rgd2D: RigidBody2D = null;

    @property(CCFloat)
    rotateSpeed: number = 30;
    @property(AudioClip)
    clickAudio: AudioClip = null;

    private _canControl: boolean = false
    onLoad () {
        input.on(Input.EventType.TOUCH_START, this.onTouchStart, this);

        let collider = this.getComponent(Collider2D);
        if (collider) {
            collider.on(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this);
            collider.on(Contact2DType.END_CONTACT, this.onEndContact, this);
        }
        this.rgd2D = this.getComponent(RigidBody2D);
    }
    protected update (deltaTime: number) {
        if(!this._canControl)return
        this.node.angle -= this.rotateSpeed * deltaTime;
        if (this.node.angle < -60) {
            this.node.angle = -60
        }
    }
    onDestroy () {
        input.off(Input.EventType.TOUCH_START, this.onTouchStart, this);
        let collider = this.getComponent(Collider2D);
        if (collider) {
            collider.off(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this);
            collider.off(Contact2DType.END_CONTACT, this.onEndContact, this);
        }
    }

    onTouchStart(event: EventTouch) {
        if(!this._canControl)return
        this.rgd2D.linearVelocity = new Vec2(0, 10);
        this.node.angle = 20
        AudioMgr.inst.playOneShot(this.clickAudio)
    }
    public enableControl(){
        this.getComponent(Animation).enabled = true
        this.rgd2D.enabled = true
        this._canControl = true
    }
    
    public disableControl(){
        this.getComponent(Animation).enabled = false
        this.rgd2D.enabled = false
        this._canControl = false
    }
    public disableControlNotRGD(){
        this.getComponent(Animation).enabled = false
        this._canControl = false
    }
    onBeginContact (selfCollider: Collider2D, otherCollider: Collider2D, contact: IPhysics2DContact | null) {
        // 只在两个碰撞体开始接触时被调用一次
        if(otherCollider.tag===Tags.PIPE || otherCollider.tag===Tags.LAND){
            this.node.emit('overGame');
        }
    }
    onEndContact (selfCollider: Collider2D, otherCollider: Collider2D, contact: IPhysics2DContact | null) {
        // 只在两个碰撞体结束接触时被调用一次
        if(otherCollider.tag === Tags.PIPE_MIDDLE){
            this.node.emit('addScore');
        }
    }
}

